import 'dart:io';
import 'dart:math';

import 'package:dio/dio.dart';
import 'package:ffmpeg_kit_flutter/ffmpeg_kit.dart';
import 'package:ffmpeg_kit_flutter/return_code.dart';
import 'package:flutter/material.dart';
import 'package:full_display/common/qxp_color.dart';
import 'package:full_display/common/qxp_style.dart';
import 'package:full_display/generated/l10n.dart';
import 'package:full_display/page/medium/local_provider.dart';
import 'package:full_display/page/single/single_api.dart';
import 'package:full_display/provide/media_provider.dart';
import 'package:full_display/unit/log/log_util.dart';
import 'package:full_display/unit/screen/screen_util1.dart';
import 'package:full_display/unit/screen/screen_utility.dart';
import 'package:full_display/unit/toast/toast_util.dart';
import 'package:full_display/unit/web_socket/web_sockect_utils.dart';
import 'package:full_display/unit/widgets/line_painter.dart';
import 'package:full_display/unit/widgets/slider/video_view.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:syncfusion_flutter_sliders/sliders.dart';
import 'package:http_parser/http_parser.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:path/path.dart' as p;
import 'package:video_player/video_player.dart';

class MediaShow extends StatefulWidget {
  final String url;
  Function(BuildContext context) tapAction;
  MediaShow({super.key, required this.url, required this.tapAction});

  @override
  State<MediaShow> createState() => _MediaShowState();
}

class _MediaShowState extends State<MediaShow> {
  late MediaVideoProvider _mediaData;
  late VideoPlayerController _controller;
  static const double DEFAULT_WIDTH = 160;
  static const double DEFAULT_HEIGHT = 160;
  final GlobalKey _globalKey = GlobalKey();
  final GlobalKey _globalVideoKey = GlobalKey();
  final GlobalKey _globalLineKey = GlobalKey();
  //视频的参数，宽，高，比例
  late double _width;
  late double _height;
  late double _x;
  late double _y;
  late double _ratio;
  late Size _videoSize;

  //临时变量
  late double _tmpW;
  late double _tmpH;
  late Offset _lastOffset;

  //背景的宽高
  late double _bgW;
  late double _bgH;

  //滑块的值
  SfRangeValues _values = SfRangeValues(0.0, 1.0);
  bool _isShowSlider = false;

  @override
  void initState() {
    super.initState();
    //一些参数的初始化
    _width = DEFAULT_WIDTH;
    _height = DEFAULT_HEIGHT;
    _x = 0;
    _y = 0;
    _ratio = _width! / _height!;
    _tmpW = _width;
    _tmpH = _height;
  }

  @override
  Widget build(BuildContext context) {
    _mediaData = context.watch<MediaVideoProvider>();
    return Container(
      color: Colors.transparent,
      width: ScreenUtil1.screenWidth,
      height: ScreenUtil1.screenHeight,
      child: Column(
        children: [
          Container(
            color: Colors.transparent,
            width: ScreenUtil1.screenWidth,
            height: ScreenUtil1.screenHeight - 400.0.H,
            child: Stack(
              children: <Widget>[
                //https://flutter.github.io/assets-for-api-docs/assets/videos/bee.mp4
                //http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4
                Container(
                  key: _globalKey,
                  color: Colors.transparent,
                  width: double.infinity,
                  height: double.infinity,
                ),
                Positioned(
                  key: _globalVideoKey,
                  left: _x,
                  top: _y,
                  child: GestureDetector(
                    onScaleEnd: scaleEnd,
                    onScaleStart: scaleStart,
                    onScaleUpdate: scaleUpdate,
                    child: VideoView(
                      rvalues: _values,
                      width: _width,
                      height: _height,
                      url: widget.url,
                      aspect: asp,
                    ),
                  ),
                ),
                Center(
                  child: GestureDetector(
                    onScaleEnd: scaleEnd,
                    onScaleStart: scaleStart,
                    onScaleUpdate: scaleUpdate,
                    child: Container(
                      key: _globalLineKey,
                      width: 200,
                      height: 200,
                      color: ColorPlate.backgroundOpacity0,
                      child: DottedBorder(
                        color: Colors.white,
                        borderType: BorderType.RRect,
                        strokeWidth: 1,
                        radius: Radius.circular(100),
                        child: ClipRRect(),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            color: ColorPlate.background,
            height: 310.0.H,
            width: ScreenUtil1.screenWidth,
            child: Column(
              children: [
                Container(
                  height: 50.0.H,
                ),
                Padding(
                  padding: EdgeInsets.all(20.0.W),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Container(
                        width: 80.0.W,
                        height: 40.0.W,
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                              //渐变位置
                              begin: Alignment.topCenter, //右上
                              end: Alignment.bottomCenter, //左下
                              //渐变颜色[始点颜色, 结束颜色]
                              colors: [
                                ColorPlate.app_blue,
                                ColorPlate.sub_blue
                              ]),
                          borderRadius:
                              BorderRadius.all(Radius.circular(4.0.H)),
                        ),
                        child: Center(
                          child: Text(
                            (_values.start / 1000).truncate().toString(),
                            style: StandardTextStyle.textWhite12Style,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                      Container(
                        width: 80.0.W,
                        height: 40.0.W,
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                              //渐变位置
                              begin: Alignment.topCenter, //右上
                              end: Alignment.bottomCenter, //左下
                              //渐变颜色[始点颜色, 结束颜色]
                              colors: [
                                ColorPlate.app_blue,
                                ColorPlate.sub_blue
                              ]),
                          borderRadius:
                              BorderRadius.all(Radius.circular(4.0.H)),
                        ),
                        child: Center(
                          child: Text(
                            (_values.end / 1000).truncate().toString(),
                            style: StandardTextStyle.textWhite12Style,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                _isShowSlider
                    ? Container(
                        width: ScreenUtil1.screenWidth - 40.0.W,
                        height: 40,
                        child: SfRangeSlider(
                          min: 0.0,
                          max: _mediaData.maxValue * 1000.0,
                          values: _values,
                          interval: 1000,
                          stepSize: 1000,
                          labelFormatterCallback:
                              (dynamic actualValue, String formattedText) {
                            // return actualValue == 1000 ? '不限' : '¥$formattedText';
                            return "";
                          },
                          inactiveColor: Colors.grey[200],
                          minorTicksPerInterval: 1,
                          onChanged: (SfRangeValues values) {
                            setState(() {
                              _values = values;
                              videoSetSeekTo((_values.start / 1000.0).toInt(),
                                  (_values.end / 1000.0).toInt());
                            });
                          },
                        ),
                      )
                    : Container(),
                Container(
                  height: 40.0.H,
                ),
                InkWell(
                  onTap: () {
                    cipeVideoSize(widget.url, context);
                    // updateVideo(widget.url, context);
                  },
                  child: Container(
                    height: 40.0.H,
                    width: ScreenUtil1.screenWidth - 40.0.W,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                          //渐变位置
                          begin: Alignment.topCenter, //右上
                          end: Alignment.bottomCenter, //左下
                          //渐变颜色[始点颜色, 结束颜色]
                          colors: [ColorPlate.app_blue, ColorPlate.sub_blue]),
                      borderRadius: BorderRadius.all(Radius.circular(20.0.H)),
                    ),
                    child: Center(
                      child: Text(
                        S.of(context).queding,
                        style: StandardTextStyle.textWhite16BoldStyle,
                      ),
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  void asp(Map m) {
    setState(() {
      _ratio = m["asp"];
      _videoSize = m["size"];
      // if (_videoSize.width >= ScreenUtil1.screenWidth) {
      //   _width = ScreenUtil1.screenWidth;
      // }
      RenderBox? renderBox1 =
          _globalLineKey.currentContext!.findRenderObject() as RenderBox?;
      var offset1 = renderBox1!.localToGlobal(Offset.zero);
      if (_videoSize.width >= _videoSize.height) {
        if (_videoSize.width >= DEFAULT_WIDTH) {
          _width = DEFAULT_WIDTH;
        }
        _height = _width / m["asp"];
        _x = offset1.dx + 20;
        _y = (200 - _height) / 2.0 + (offset1.dy - ScreenUtil1.statusBarHeight);
      } else {
        if (_videoSize.height >= DEFAULT_HEIGHT) {
          _height = DEFAULT_HEIGHT;
        }
        _width = _height * m["asp"];

        _x = (200 - _width) / 2.0 + offset1.dx;
        _y = (offset1.dy - ScreenUtil1.statusBarHeight) + 20;
      }
      _mediaData.updateMaxvalue(m["duration"]);
      _values = SfRangeValues(0.0, m["duration"] * 1000.0);
      _controller = m["con"];
      _controller.addListener(() {
        if (_controller.value.position.inSeconds >=
            (_values.end / 1000.0).toInt()) {
          Duration _p = Duration(seconds: (_values.start / 1000.0).toInt());
          _controller.seekTo(_p);
        }
        setState(() {});
      });
      print("con=====>${_controller}");
      _isShowSlider = true;
    });
  }

  //计算背景的宽高
  void getBgInfo() {
    RenderObject? renderObject = _globalKey.currentContext?.findRenderObject();
    _bgW = renderObject!.paintBounds.size.width;
    _bgH = renderObject.paintBounds.size.height;
  }

//计算视频和划线的焦点
  void getvodie() {
    RenderBox? renderBox =
        _globalVideoKey.currentContext!.findRenderObject() as RenderBox?;
    var offset = renderBox!.localToGlobal(Offset.zero);
    print("renderBox=======>${offset.dx}======${offset.dy}");

    RenderBox? renderBox1 =
        _globalLineKey.currentContext!.findRenderObject() as RenderBox?;
    var offset1 = renderBox1!.localToGlobal(Offset.zero);
    print("renderBox1=======>${offset1.dx}======${offset1.dy}");
  }

  //开始缩放
  void scaleStart(ScaleStartDetails details) {
    _tmpW = _width;
    _tmpH = _height;
    _lastOffset = details.focalPoint;
    getBgInfo();
  }

  //缩放更新
  void scaleUpdate(ScaleUpdateDetails details) {
    setState(() {
      _width = _tmpW * details.scale;
      _height = _tmpH * details.scale;
      _x += (details.focalPoint.dx - _lastOffset.dx);
      _y += (details.focalPoint.dy - _lastOffset.dy);
      //边界判定，保持宽高比
      if (_width > _bgW * 2) {
        _width = _bgW * 2;
        _height = _width / _ratio;
      }
      // if (_height > _bgH) {
      //   _height = _bgH;
      //   _width = _height * _ratio;
      // }
      if (_x < -(_width - 50)) {
        _x = -(_width - 50);
      }
      if (_y < -(_height - 50)) {
        _y = -(_height - 50);
      }
      // if(_x > _bgW-_width){
      //   _x = _bgW-_width;
      // }
      if (_x > (_bgW - 50)) {
        _x = (_bgW - 50);
      }
      if (_y > (_bgH - 50)) {
        _y = (_bgH - 50);
      }
      _lastOffset = details.focalPoint;
    });
  }

  //缩放结束
  void scaleEnd(ScaleEndDetails details) {
    _tmpW = _width;
    _tmpH = _height;
    print(
        "_tmpW=========${_tmpW}====_tmpH=====${_tmpH}=====_ratio====${_ratio}");
    //边界判定，保持宽高比
    if (_tmpW > _tmpH) {
      if (_width < DEFAULT_WIDTH) {
        _width = DEFAULT_WIDTH;
        _height = _width / _ratio;
      }
    } else {
      if (_height < DEFAULT_HEIGHT) {
        _height = DEFAULT_HEIGHT;
        _width = _height * _ratio;
      }
    }
  }

  //控制视频
  videoSetSeekTo(int start, int end) {
    print("=====>${_controller}");

    Duration _position = Duration(seconds: start);
    Duration _positionEnd = Duration(seconds: end);
    _controller.seekTo(_position);
  }

//裁剪视频的尺寸
  Future<void> cipeVideoSize(String path, BuildContext context) async {
    //获取路径的扩展
    final extension = p.extension(path);
    print("path=====${extension}");

    RenderObject? renderObject =
        _globalVideoKey.currentContext?.findRenderObject();
    double w = renderObject!.paintBounds.size.width;
    double h = renderObject.paintBounds.size.height;
    print("w1=======>${w}======${h}");

    print("_videoSize=======>${_videoSize}");
    double wratio = w / _videoSize.width;
    double hratio = h / _videoSize.height;
    print("wratio=======>${wratio}======${hratio}");

    RenderBox? renderBox =
        _globalVideoKey.currentContext!.findRenderObject() as RenderBox?;
    var offset = renderBox!.localToGlobal(Offset.zero);
    RenderBox? renderBox1 =
        _globalLineKey.currentContext!.findRenderObject() as RenderBox?;
    var offset1 = renderBox1!.localToGlobal(Offset.zero);

    print("dx=======>${offset1.dx}======${offset.dx}");
    double x = 0.0;
    if ((offset.dx - offset1.dx) > 0) {
      x = 0;
    } else if ((offset.dx - offset1.dx) == 0) {
      x = 0;
    } else if ((offset.dx - offset1.dx) < 0) {
      x = offset1.dx - offset.dx;
    }
    x = x / wratio;
    print("dy=======>${offset1.dy}======${offset.dy}");
    double y = 0.0;
    if ((offset.dy - offset1.dy) > 0) {
      y = 0;
    } else if ((offset.dy - offset1.dy) == 0) {
      y = 0;
    } else if ((offset.dy - offset1.dy) < 0) {
      y = offset1.dy - offset.dy;
      print("yy-----------${y}");
    }
    y = y / wratio;
    print("xy=======>${x}======${y}");

    double wh = 200 / wratio;
    double videoW = wh;
    if (videoW > _videoSize.width) {
      videoW = _videoSize.width;
    }

    double videoH = wh;
    if (videoH > _videoSize.height) {
      videoH = _videoSize.height;
    }
    Directory tempDir = await getTemporaryDirectory();
    var tmpVideo = '${tempDir.path}/out$extension';
    // String fileLeng = getFileSizeString(bytes: File(tmpVideo).lengthSync());
    // logD("视频大小：====${fileLeng}");
    File(tmpVideo).delete();
    print("tempDir=====>${tmpVideo}");

    // var cmd = ' -i $path -vf crop=$videoW:$videoH:$x:$y  $tmpVideo';
    var cmd =
        ' -i $path -vf crop=$videoW:$videoH:$x:$y  -ss ${(_values.start / 1000).truncate().toString()} -to ${(_values.end / 1000).truncate().toString()} $tmpVideo';
    print('命令是：' + cmd);
    showLoading(context, '处理中，时间可能比较久\n请耐心等待');
    FFmpegKit.execute(cmd).then((session) async {
      final returnCode = await session.getReturnCode();
      if (ReturnCode.isSuccess(returnCode)) {
        // cipeVideo(tmpVideo);
        logD("裁剪过视频大小：====${tmpVideo}");
        updateVideo(tmpVideo, context);
      } else if (ReturnCode.isCancel(returnCode)) {
        Navigator.pop(context);
      } else {
        Navigator.pop(context);
      }
    });
  }

//裁剪视频长短
  // void cipeVideo(String path) async {
  //   //获取路径的扩展
  //   final extension = p.extension(path);
  //   print("path=====${extension}");

  //   Directory tempDir = await getTemporaryDirectory();
  //   var tmpVideo = '${tempDir.path}/out$extension';
  //   var tmpVideo1 = '${tempDir.path}/out1$extension';
  //   File(tmpVideo1).delete();
  //   print("tempDir=====>${tmpVideo1}");
  //   var cmd =
  //       ' -i $tmpVideo -ss ${(_values.start / 1000).truncate().toString()} -to ${(_values.end / 1000).truncate().toString()} $tmpVideo1';
  //   FFmpegKit.execute(cmd).then((session) async {
  //     final returnCode = await session.getReturnCode();
  //     if (ReturnCode.isSuccess(returnCode)) {
  //       print("1==========>");
  //       updateVideo(tmpVideo1, context);
  //     } else if (ReturnCode.isCancel(returnCode)) {
  //       print("1-------------->");
  //       Navigator.pop(context);
  //     } else {
  //       print("1++++++++++++++>");
  //       Navigator.pop(context);
  //     }
  //   });
  // }

  //发送命令 并 上传视频
  void updateVideo(String path, BuildContext context) async {
    if (path.isNotEmpty) {
      // ProgressHUD.showLoadingText("处理中，时间可能比较久\n请耐心等待");
      // showToast("处理中，时间可能比较久\n请耐心等待");
      WebSocketUtils().sendCustomMessage(65);
      FormData formdata = FormData.fromMap({
        "file": await MultipartFile.fromFile(
          path,
          filename: "file.mov",
          contentType: MediaType.parse("video/mov"),
        ),
      });
      // print("========file===${formdata}");
      debugPrint("========file===${formdata}");
      SingleApi().updateVideo(
        formdata,
        failure: (error) {
          // ProgressHUD.hide();
          print("=============>成功");
          // Navigator.pop(context);
          widget.tapAction(context);
        },
        success: (data) {
          // ProgressHUD.hide();
          print("=============>失败");
          // Navigator.pop(context);
          widget.tapAction(context);
        },
      );
    }
  }

  String getFileSizeString({required int bytes, int decimals = 0}) {
    if (bytes <= 0) return "0 Bytes";
    const suffixes = [" Bytes", "KB", "MB", "GB", "TB"];
    var i = (log(bytes) / log(1024)).floor();
    return ((bytes / pow(1024, i)).toStringAsFixed(decimals)) + suffixes[i];
  }
}
